<template>
    <div class="topic-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="标题名称:">
                                <el-input 
                                    v-model="searchForm.name" 
                                    placeholder="输入标题名称" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="语言:">
                                <el-select 
                                    v-model="searchForm.language" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 120px"
                                >
                                    <el-option label="中文" value="zh-CN" />
                                    <el-option label="英文" value="en" />
                                </el-select>
                            </el-form-item>
                            <!-- <el-form-item label="创建时间:">
                                <el-date-picker
                                    v-model="searchForm.dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="请选择日期"
                                    end-placeholder="请选择日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 240px"
                                />
                            </el-form-item> -->
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                    </div>
                </div>
            </el-card>
        </div>

         <!-- 新增按钮 -->
         <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAddTopic">新增分类</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="name" label="标题名称" />
                    <el-table-column prop="language" label="语言" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="row.language === 'zh-CN' ? 'primary' : 'success'">
                                {{ row.language === 'zh-CN' ? '中文' : '英文' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="imageUrl" label="分类图片" align="center">
                        <template #default="{ row }">
                            <el-image 
                                v-if="row.imageUrl" 
                                :src="row.imageUrl" 
                                :preview-src-list="[row.imageUrl]"
                                style="width: 60px; height: 40px; border-radius: 4px;"
                                fit="cover"
                            />
                            <span v-else class="no-image">暂无图片</span>
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDateTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTopicCategoryPage, deleteTopicCategory } from '@/api/content/topic-category';
import { CirclePlusFilled } from '@element-plus/icons-vue';


const router = useRouter();

// 定义话题分类数据类型
interface TopicCategoryItem {
    id: string;
    language: string;
    name: string;
    imageUrl: string;
    createTime: string;
    updateTime: string;
}

// 搜索表单
const searchForm = reactive({
    name: '',
    language: '',
    dateRange: []
});

// 表格数据
const loading = ref(false);
const tableData = ref<TopicCategoryItem[]>([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 格式化时间
const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '-';
    try {
        const date = new Date(dateStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    } catch (error) {
        return dateStr;
    }
};

// 加载数据
const loadData = async () => {
    try {
        loading.value = true;
        
        // 构建查询参数
        const params = {
            current: pagination.current,
            size: pagination.size,
            // 搜索条件
            ...(searchForm.name && { name: searchForm.name }),
            ...(searchForm.language && { language: searchForm.language }),
            ...(searchForm.dateRange && searchForm.dateRange.length === 2 && {
                startTime: searchForm.dateRange[0],
                endTime: searchForm.dateRange[1]
            })
        };
        
        console.log('请求参数:', params);
        
        const res = await getTopicCategoryPage(params);
        console.log('API响应:', res);
        
        // 处理不同的响应数据结构
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            // 标准分页响应结构
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            // 处理错误响应
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取话题分类数据失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取话题分类数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
        tableData.value = [];
        pagination.total = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    loadData();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    loadData();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    loadData();
};

// 新增分类
const handleAddTopic = () => {
    router.push('/topic-form');
};

// 编辑分类
const handleEdit = (row: TopicCategoryItem) => {
    router.push(`/topic-form/${row.id}`);
};

// 删除方法
const handleDelete = async (row: TopicCategoryItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除话题分类 "${row.name}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        // 调用删除API
        loading.value = true;
        const res = await deleteTopicCategory(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功');
            loadData(); // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败';
            ElMessage.error(errorMsg);
        }
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除话题分类失败:', error);
            ElMessage.error('删除失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 页面初始化
onMounted(() => {
    loadData();
});
</script>

<style scoped>
.topic-list-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
    margin-bottom: 20px;
}

.add-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-left {
    flex: 1;
}

.search-right {
    display: flex;
    gap: 12px;
    margin-left: 20px;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

/* 表格区域样式 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域样式 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
    width: 100%;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background: #fafafa;
}

/* 分页样式 */
:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-pagination .el-pagination__jump) {
    margin-left: 16px;
}

/* 图片样式 */
.no-image {
    color: #999;
    font-size: 12px;
}

:deep(.el-image) {
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .topic-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
        padding: 15px;
    }
    
    .search-right {
        margin-left: 0;
        width: 100%;
        justify-content: flex-start;
    }
    
    .search-form .el-form-item {
        margin-bottom: 15px;
    }
    
    .pagination-content {
        gap: 15px;
        padding: 15px;
        flex-direction: row;
        justify-content: flex-end;
    }
    
    .pagination-info {
        text-align: center;
        font-size: 12px;
    }
}
</style>
